#include "AQthreadpool.h"
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>

const int NUM = 2;

typedef struct Task
{
    void (*func)(void *arg);
    void *arg;
} Task;

struct Threadpool
{
    //任务队列
    Task *taskQ;
    int queueCapacity;
    int queueSize;
    int queueFront;
    int queueRear;

    pthread_t managerID;  //管理者
    pthread_t *threadIDs; //工作者
    int minnum;           //最小线程数
    int maxnum;
    int busynum; //忙线程
    int livenum; //存活线程
    int exitnum; //要杀死的线程
    pthread_mutex_t mutexpool;
    pthread_mutex_t mutexbusy;
    pthread_cond_t notfull;
    pthread_cond_t notempty;

    int shutdown; //要不要销毁线程池
};

Threadpool *threadpoolcreate(int min, int max, int qusize)
{
    Threadpool *pool = (Threadpool *)malloc(sizeof(Threadpool));
    do
    {
        if (pool == NULL)
        {
            printf("malloc threadpool fail...\n");
            break;
        }
        pool->threadIDs = (pthread_t *)malloc(sizeof(pthread_t) * max);
        if (pool->threadIDs == NULL)
        {
            printf("malloc threadIDs fail...\n");
            break;
        }
        memset(pool->threadIDs, 0, sizeof(pool->threadIDs));
        pool->minnum = min;
        pool->maxnum = max;
        pool->busynum = 0;
        pool->livenum = min;
        pool->exitnum = 0;

        if (pthread_mutex_init(&pool->mutexpool, NULL) != 0 ||
            pthread_mutex_init(&pool->mutexbusy, NULL) != 0 ||
            pthread_cond_init(&pool->notempty, NULL) != 0 ||
            pthread_cond_init(&pool->notfull, NULL) != 0)
        {
            printf("Fail\n");
            break;
        }

        pool->taskQ = (Task *)malloc(qusize * sizeof(Task));
        pool->queueCapacity = qusize;
        pool->queueSize = 0;
        pool->queueFront = 0;
        pool->queueRear = 0;

        pool->shutdown = 0;

        ///创建线程
        pthread_create(&pool->managerID, NULL, manager, pool);
        int i;
        for (i = 0; i < min; i++)
        {
            pthread_create(&pool->threadIDs[i], NULL, worker, pool);
        }
        return pool;
    } while (0);

    if (pool && pool->threadIDs)
        free(pool->threadIDs);
    if (pool && pool->taskQ)
        free(pool->taskQ);
    if (pool)
        free(pool);

    return NULL;
}

void threadpooladd(Threadpool *pool, void (*func)(void *), void *arg)
{
    pthread_mutex_lock(&pool->mutexpool);
    while (pool->queueSize == pool->queueCapacity && !pool->shutdown)
    {
        pthread_cond_wait(&pool->notfull, &pool->mutexpool);
    }

    if (pool->shutdown)
    {
        pthread_mutex_unlock(&pool->mutexpool);
        return;
    }

    pool->taskQ[pool->queueRear].func = func;
    pool->taskQ[pool->queueRear].arg = arg;
    pool->queueRear = (pool->queueRear + 1) % pool->queueCapacity;
    pool->queueSize++;
    pthread_cond_signal(&pool->notempty);
    pthread_mutex_unlock(&pool->mutexpool);
}

int threadpoolbusynum(Threadpool *pool)
{
    pthread_mutex_lock(&pool->mutexbusy);
    int bn = pool->busynum;
    pthread_mutex_unlock(&pool->mutexbusy);
    return bn;
}

int threadpoolalivenum(Threadpool *pool)
{
    pthread_mutex_lock(&pool->mutexpool);
    int bn = pool->livenum;
    pthread_mutex_unlock(&pool->mutexpool);
    return bn;
}

int threadpooldestory(Threadpool *pool)
{
    if (pool == NULL)
    {
        return -1;
    }
    pool->shutdown = 1;
    pthread_join(pool->managerID, NULL);
    int i;
    for (i = 0; i < pool->livenum; i++)
    {
        pthread_cond_signal(&pool->notempty);
    }
    if (pool->taskQ)
    {
        free(pool->taskQ);
    }
    if (pool->threadIDs)
    {
        free(pool->threadIDs);
    }

    pthread_mutex_destroy(&pool->mutexpool);
    pthread_mutex_destroy(&pool->mutexbusy);
    pthread_cond_destroy(&pool->notempty);
    pthread_cond_destroy(&pool->notfull);

    free(pool);
    pool = NULL;

    return 0;
}

void threadexit(Threadpool *pool)
{
    int i;
    pthread_t tid = pthread_self();
    for (i = 0; i < pool->maxnum; i++)
    {
        if (pool->threadIDs[i] == tid)
        {
            pool->threadIDs[i] = 0;
            printf("threadexit called,%ld exiting...\n", pthread_self());
            break;
        }
    }
    pthread_exit(NULL);
}

void *worker(void *arg)
{
    Threadpool *pool = (Threadpool *)arg;
    while (1)
    {
        pthread_mutex_lock(&pool->mutexpool);
        while (pool->queueSize == 0 && !pool->shutdown)
        {
            //阻塞工作线程
            pthread_cond_wait(&pool->notempty, &pool->mutexpool);

            //判断是否销毁线程
            if (pool->exitnum > 0)
            {
                pool->exitnum--;
                if (pool->livenum > pool->minnum)
                {
                    pool->livenum--;
                    pthread_mutex_unlock(&pool->mutexpool);
                    threadexit(pool);
                }
            }
        }

        //判断线程池是否关闭
        if (pool->shutdown)
        {
            pthread_mutex_unlock(&pool->mutexpool);
            threadexit(pool);
        }

        //从任务队列取任务
        Task task;
        task.func = pool->taskQ[pool->queueFront].func;
        task.arg = pool->taskQ[pool->queueFront].arg;

        pool->queueFront = (pool->queueFront + 1) % pool->queueCapacity;
        pool->queueSize--;

        pthread_cond_signal(&pool->notfull); //唤醒生产者
        pthread_mutex_unlock(&pool->mutexpool);

        printf("thread %ld start working...\n", pthread_self());
        pthread_mutex_lock(&pool->mutexbusy);
        pool->busynum++;
        pthread_mutex_unlock(&pool->mutexbusy);
        task.func(task.arg);
        ///free(task.arg);
        task.arg = NULL;
        printf("thread %ld end working...\n", pthread_self());

        pthread_mutex_lock(&pool->mutexbusy);
        pool->busynum--;
        pthread_mutex_unlock(&pool->mutexbusy);
    }
    return NULL;
}

void *manager(void *arg)
{
    Threadpool *pool = (Threadpool *)arg;
    while (!pool->shutdown)
    {
        //sleep(3);

        //获得线程池中任务的数量和当前线程的数量
        pthread_mutex_lock(&pool->mutexpool);
        int queuesize = pool->queueSize;
        int livenum = pool->livenum;
        pthread_mutex_unlock(&pool->mutexpool);

        //获得忙线程数量
        pthread_mutex_lock(&pool->mutexbusy);
        int busynum = pool->busynum;
        pthread_mutex_unlock(&pool->mutexbusy);

        //添加线程
        //任务个数>存活的线程个数 && 存活的线程数<最大线程数

        if (queuesize > livenum && livenum < pool->maxnum)
        {
            pthread_mutex_lock(&pool->mutexpool);

            int counter = 0, i;
            for (i = 0; i < pool->maxnum && counter < NUM && queuesize > livenum && livenum < pool->maxnum; i++)
            {
                if (pool->threadIDs[i] == 0)
                {
                    pthread_create(&pool->threadIDs[i], NULL, worker, pool);
                    counter++;
                    pool->livenum++;
                }
            }
            pthread_mutex_unlock(&pool->mutexpool);
        }
        //销毁线程
        //忙线程*2 < 存活的线程数 && 存活的线程 > 最小线程数
        if (busynum * 2 < livenum && livenum > pool->minnum)
        {
            pthread_mutex_lock(&pool->mutexpool);
            pool->exitnum = NUM;
            pthread_mutex_unlock(&pool->mutexpool);
            //让工作线程自杀
            int i;
            for (i = 0; i < NUM; i++)
            {
                pthread_cond_signal(&pool->notempty);
            }
        }
    }
    return NULL;
}
